import React, { useEffect, useRef, useState } from 'react'
import { Header, AlertTip, RouterView } from 'src/components'
import { signout } from 'src/api/getData'
import { imgBaseUrl } from 'src/config/env'
import { removeStore } from 'src/config/mUtils'
import { useSelector, useDispatch } from 'react-redux'
import { Link, useHistory } from 'react-router-dom'
import classNames from 'classnames'
import { OUT_LOGIN } from 'src/redux/action-type'
import routerData from './routerData'
import './index.scss'

const ProfileInfo = (props) => {
    const { userInfo } = useSelector(state => state)
    const dispatch = useDispatch()
    const history = useHistory()
    const [username, setUsername] = useState('')    //用户名
    const [infotel, setInfotel] = useState('')     //用户手机
    const [avatar, setAvatar] = useState('')      //用户头像
    const [show, setShow] = useState(false)     //显示提示框
    const [isEnter, setIsEnter] = useState(true)  //是否登录
    const [isLeave, setIsLeave] = useState(false) //是否退出
    const [showAlert, setShowAlert] = useState(false)
    const [alertText, setAlertText] = useState()
    const timerRef = useRef()

    useEffect(() => {
        if (userInfo && userInfo.user_id) {
            setUsername(userInfo.username)
            setInfotel(userInfo.mobile)
            setAvatar(userInfo.avatar)
        }
    }, [userInfo])

    useEffect(() => {
        return () => {
            clearTimeout(timerRef.current)
        }
    }, [])

    const exitlogin = () => {
        setShow(true)
        setIsEnter(true)
        setIsLeave(false)
    }
    const waitingThing = () => {
        //取消推出
        clearTimeout(timerRef.current)
        setIsEnter(false);
        setIsLeave(true);
        timerRef.current = setTimeout(() => {
            clearTimeout(timerRef.current)
            setShow(false)
        }, 200)
    }
    //退出登录
    const outLogin = async () => {
        dispatch({
            type: OUT_LOGIN
        })
        waitingThing();
        history.go(-1);
        removeStore('user_id')
        await signout();
    }
    const changePhone = () => {
        setShowAlert(true)
        setAlertText('请在手机APP中设置')
    }
    const uploadAvatar = async () => {
        //上传头像
        if (userInfo) {
            let input = document.querySelector('.profileinfopanel-upload')
            let data = new FormData();
            data.append('file', input.files[0]);
            try {
                let response = await fetch('/eus/v1/users/' + userInfo.user_id + '/avatar', {
                    method: 'POST',
                    credentials: 'include',
                    body: data
                })
                let res = await response.json();
                if (res.status === 1) {
                    userInfo.avatar = res.image_path;
                }
            } catch (error) {
                setShowAlert(true)
                setAlertText('上传失败')
                throw new Error(error);
            }
        }
    }

    const onClose = () => {
        setShowAlert(false)
    }

    return <div className="page_profile_info">
        <Header title="账户信息" goBack></Header>
        <section className="profile-info">
            <section className="headportrait">
                <input type="file" className="profileinfopanel-upload" onChange={uploadAvatar} />
                <h2>头像</h2>
                <div className="headportrait-div">
                    {userInfo ?
                        <img src={imgBaseUrl + avatar} className="headportrait-div-top" alt="" />
                        :
                        <span className="headportrait-div-top">
                            <svg>
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#avatar-default"></use>
                            </svg>
                        </span>
                    }
                    <span className="headportrait-div-bottom">
                        <svg fill="#d8d8d8">
                            <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                        </svg>
                    </span>
                </div>
            </section>
            <Link to="/profile/info/setusername" className="info-router">
                <section className="headportrait headportraitwo">
                    <h2>用户名</h2>
                    <div className="headportrait-div">
                        <p>{username}</p>
                        <span className="headportrait-div-bottom">
                            <svg fill="#d8d8d8">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </span>
                    </div>
                </section>
            </Link>
            <Link to="/profile/info/address" className="info-router">
                <section className="headportrait headportraitwo headportraithree">
                    <h2>收货地址</h2>
                    <div className="headportrait-div">
                        <span className="headportrait-div-bottom">
                            <svg fill="#d8d8d8">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </span>
                    </div>
                </section>
            </Link>
            <section className="bind-phone">
                账号绑定
            </section>
            <section className="info-router" onClick={changePhone}>
                <section className="headportrait headportraitwo headportraithree">
                    <h2><img src="/images/bindphone.png" style={{ display: 'inline-block', marginRight: '.4rem' }} alt="" />手机</h2>
                    <div className="headportrait-div">
                        <p>{infotel}</p>
                        <span className="headportrait-div-bottom">
                            <svg fill="#d8d8d8">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </span>
                    </div>
                </section>
            </section>
            <section className="bind-phone">
                安全设置
            </section>
            <Link to="/forget" className="info-router">
                <section className="headportrait headportraitwo headportraithree">
                    <h2>登录密码</h2>
                    <div className="headportrait-div">
                        <p>修改</p>
                        <span className="headportrait-div-bottom">
                            <svg fill="#d8d8d8">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </span>
                    </div>
                </section>
            </Link>
            <section className="exitlogin" onClick={exitlogin}>退出登录</section>
        </section>
        {
            show && <section className="coverpart">
                <section className="cover-background"></section>
                <section className={classNames('cover-content', { 'cover-animate': isEnter, 'cover-animate-leave': isLeave })}>
                    <div className="sa-icon">
                        <span className="sa-body"></span>
                        <span className="sa-dot"></span>
                    </div>
                    <h2>是否退出登录</h2>
                    <div className="sa-botton">
                        <button className="waiting" onClick={waitingThing}>再等等</button>
                        <div style={{
                            display: 'inline-block'
                        }}>
                            <button className="quitlogin" onClick={outLogin}>退出登录</button>
                        </div>
                    </div>
                </section>
            </section>
        }
        {showAlert && <AlertTip onClose={onClose} alertText={alertText}></AlertTip>}
        <RouterView data={routerData} />
    </div>
}

export default ProfileInfo